package com.example.smartcamera.slice;

import com.example.smartcamera.ResourceTable;
import com.example.smartcamera.utils.LogUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.Surface;
import ohos.agp.graphics.SurfaceOps;
import ohos.global.resource.RawFileDescriptor;
import ohos.media.common.Source;
import ohos.media.player.Player;
import ohos.agp.components.Component;
import ohos.media.common.sessioncore.AVElement;
import com.example.smartcamera.utils.VideoElementManager;
import com.example.smartcamera.utils.VideoPlayerPlugin;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PlayBackAbilitySlice extends AbilitySlice {
    private static final int TAB_WIDTH = 64;
    private static final int TAB_PADDING_LEFT = 12;
    private static final int TAB_PADDING_RIGHT = 12;
    private static final int TAB_PADDING_BOTTOM = 12;
    private static final int TAB_PADDING_TOP = 12;
    private TabList tabList2;
    private ListContainer listContainer;
    private List<AVElement> avElements = new ArrayList<>();
    private VideoElementsListItemProvider videoElementsListItemProvider;
    private VideoPlayerPlugin videoPlayerPlugin;
    //得到类的简写名称
    private static final String TAG = PlayBackAbilitySlice.class.getSimpleName();
    private String url = "entry/resources/base/media/gubeishuizhen.mp4";
    //图像渲染在屏幕上需要使用SurfaceProvider，该类控制surface的尺寸和格式，修改surface的像素，监视surface的变化等等。
    private SurfaceProvider surfaceProvider;
    //播放媒体资源，特别是视频资源，我们当然需要有 View 去渲染，
    // 鸿蒙系统 API 需要设置的 View 是 Surface
    private Surface surface;
    private Player player;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_play_back);
        //初始化布局，各种按钮
        initComponents();
        addTabSelectedListener();
        //创建SurfaceProvider
        addSurfaceProvider();
    }
    class VideoElementsListItemProvider extends BaseItemProvider {
        @Override
        public int getCount() {
            return avElements.size();
        }

        @Override
        public AVElement getItem(int position) {
            return avElements.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
            AVElement item = avElements.get(position);
            if (component == null) {
                String itemText = item.getAVDescription().getTitle().toString();
                Text text = (Text) LayoutScatter.getInstance(PlayBackAbilitySlice.this)
                        .parse(ResourceTable.Layout_list_item, null, false);
                text.setText(itemText);
                return text;
            } else {
                return component;
            }
        }
    }
    private void initComponents() {
        videoPlayerPlugin = new VideoPlayerPlugin(getApplicationContext());
        tabList2 = findComponentById(ResourceTable.Id_tab_list_play_back);
        initTab();
        Component playButton = findComponentById(ResourceTable.Id_play_button);
        Component pauseButton = findComponentById(ResourceTable.Id_stop_button);
        Component replayButton = findComponentById(ResourceTable.Id_replay_button);
        Component deleteButton = findComponentById(ResourceTable.Id_delete_button);
        listContainer = findComponentById(ResourceTable.Id_listContainer);

        playButton.setClickedListener((Component component) -> videoPlayerPlugin.startPlay());
        pauseButton.setClickedListener(component -> pauseplay());
        replayButton.setClickedListener(component -> replay());
        deleteButton.setClickedListener(component -> delete());
        listContainer.setItemClickedListener((listRoom, component, position, l) -> play(position));
        videoElementsListItemProvider = new VideoElementsListItemProvider();

        VideoElementManager videoElementManager = new VideoElementManager(getApplicationContext());
        avElements = videoElementManager.getAvElements();
        listContainer.setItemProvider(videoElementsListItemProvider);
    }
    //初始化导航栏
    private void initTab() {
        if (tabList2.getTabCount() == 0) {
            tabList2.addTab(createTab("实时"));
            tabList2.addTab(createTab("相册"));
            tabList2.addTab(createTab("回放"));
            tabList2.addTab(createTab("我的"));
            tabList2.setFixedMode(true);
            tabList2.getTabAt(2).select();
            tabList2.getTabAt(0).setClickedListener(lisener->present(new RealTimeAbilitySlice() , new Intent()));
            tabList2.getTabAt(1).setClickedListener(lisener->present(new PhotoAbilitySlice() , new Intent()));
            tabList2.getTabAt(2).setClickedListener(lisener->present(new PlayBackAbilitySlice() , new Intent()));
            tabList2.getTabAt(3).setClickedListener(lisener->present(new MineAbilitySlice() , new Intent()));
//            tabContent.setText("Select the " + tabList.getTabAt(0).getText());
        }
    }


    private void addSurfaceProvider() {
        //图像渲染在屏幕上需要使用SurfaceProvider
        surfaceProvider = new SurfaceProvider(this);

        if (surfaceProvider.getSurfaceOps().isPresent()) {
            //getSurfaceOps().get().addCallback()方法设置回调，这样可以通过回调将SurfaceProvider和设备相机相关联。
            surfaceProvider.getSurfaceOps().get().addCallback(new PlayBackAbilitySlice.SurfaceCallBack());
            surfaceProvider.pinToZTop(true);//pinToZTop()方法使surfaceview置于屏幕布局最顶层显示
        }

        DirectionalLayout directionalLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_directionalLayout);
        //addComponent()方法将SurfaceProvider添加到整体布局中。
        directionalLayout.addComponent(surfaceProvider);
    }

    class SurfaceCallBack implements SurfaceOps.Callback {
        @Override
        public void surfaceCreated(SurfaceOps callbackSurfaceOps) {
            if (surfaceProvider.getSurfaceOps().isPresent()) {
                surface = surfaceProvider.getSurfaceOps().get().getSurface();
                LogUtil.info(TAG, "surface set");
            }
        }

        @Override
        public void surfaceChanged(SurfaceOps callbackSurfaceOps, int format, int width, int height) {
            LogUtil.info(TAG, "surface changed");
        }

        @Override
        public void surfaceDestroyed(SurfaceOps callbackSurfaceOps) {
            LogUtil.info(TAG, "surface destroyed");
        }
    }

    private synchronized void play(int position) {
        //初始化Player，参数是应用上下文。联系你整个app的生命周期与资源调用
        AVElement item = avElements.get(position);
        videoPlayerPlugin.startPlay(videoElementsListItemProvider.getItem(position), surface);
        player = new Player(getContext());
        RawFileDescriptor fd = null;
        try {
            fd = getContext().getResourceManager().getRawFileEntry(url).openRawFileDescriptor();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Source source = new Source(fd.getFileDescriptor(), fd.getStartPosition(), fd.getFileSize());
        player.setSource(source);
        //设置视频播放的窗口。
        player.setVideoSurface(surface);
        LogUtil.info(TAG, source.getUri());
        player.setPlayerCallback(new PlayBackAbilitySlice.VideoCallBack());
        //准备播放。
        player.prepare();
        //开始播放
        player.play();
    }

    public synchronized void pauseplay() {
        if (player == null) {
            return;
        }
        player.pause();
        LogUtil.info(TAG, "player pause");
    }
    public synchronized void delete() {
        if (player == null) {
            return;
        }
        player.stop();
        player.release();
        LogUtil.info(TAG, "delete");
    }
    public synchronized void replay() {
        if (player == null) {
            return;
        }
        player.rewindTo(player.getCurrentTime() + 2000);
        LogUtil.info(TAG, "seek" + player.getCurrentTime());
    }


    //添加点击功能（在这里做ability跳转）
    private void addTabSelectedListener() {
        tabList2.addTabSelectedListener(new TabList.TabSelectedListener() {
            @Override
            public void onSelected(TabList.Tab tab) {
            }

            @Override
            public void onUnselected(TabList.Tab tab) {
            }

            @Override
            public void onReselected(TabList.Tab tab) {
            }
        });
    }

    //创建下方导航栏
    private TabList.Tab createTab(String text) {
        TabList.Tab tab = tabList2.new Tab(this);
        tab.setText(text);
        tab.setMinWidth(TAB_WIDTH);
        tab.setPadding(TAB_PADDING_LEFT, TAB_PADDING_TOP, TAB_PADDING_RIGHT, TAB_PADDING_BOTTOM);
        return tab;
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
    //设置各种异常信息
    private static class VideoCallBack implements Player.IPlayerCallback {
        @Override
        public void onPrepared() {
            LogUtil.info(TAG, "onPrepared");
        }

        @Override
        public void onMessage(int type, int extra) {
            LogUtil.info(TAG, "onMessage" + type);
        }

        @Override
        public void onError(int errorType, int errorCode) {
            LogUtil.error(TAG, "onError" + errorType);
        }

        @Override
        public void onResolutionChanged(int width, int height) {
            LogUtil.info(TAG, "onResolutionChanged" + width);
        }

        @Override
        public void onPlayBackComplete() {
            LogUtil.info(TAG, "onPlayBackComplete");
        }

        @Override
        public void onRewindToComplete() {
            LogUtil.info(TAG, "onRewindToComplete");
        }

        @Override
        public void onBufferingChange(int percent) {
            LogUtil.info(TAG, "onBufferingChange" + percent);
        }

        @Override
        public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {
            LogUtil.info(TAG, "onNewTimedMetaData" + mediaTimedMetaData.toString());
        }

        @Override
        public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {
            LogUtil.info(TAG, "onNewTimedMetaData" + mediaTimeInfo.toString());
        }
    }
}
